<script setup>
import { Money } from "@element-plus/icons-vue";
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import axios from "axios";
import {userStore} from "@/store/index.js";
import router from "@/router/index.js";

const userItemStore = userStore()
// 当前选中的门店
const selectedStore = ref("dayuecheng");
let orderChart = null;
let paymentChart = null;
let barChart = null;
let lineChart = null; // 新增折线图实例

onMounted(() => {

  if(userItemStore.loggedIn == false){
    router.push("/login")
  }
  // 初始化图表
  orderChart = echarts.init(document.getElementById("orderChart"));
  paymentChart = echarts.init(document.getElementById("paymentChart"));
  barChart = echarts.init(document.getElementById("barChart"));
  lineChart = echarts.init(document.getElementById("lineChart")); // 初始化折线图

  getOrderData();
  getPaymentData();
  getBarChartData();
  getLineChartData(); // 获取折线图数据
});

// 获得图表数据
const getOrderData = () => {
  axios.get("/dashboard/getOrderChartData").then((res) => {
    const option = {
      series: [
        {
          type: "pie",
          data: res.data,
          label: {
            show: true,
            position: "outside",
            formatter: "{b}: {d}%",
          },
        },
      ],
    };
    orderChart.setOption(option);
  });
};

const getPaymentData = () => {
  axios.get("/dashboard/getPaymentChartData").then((res) => {
    const option = {
      series: [
        {
          type: "pie",
          data: res.data,
          label: {
            show: true,
            position: "outside",
            formatter: "{b}: {d}%",
          },
        },
      ],
    };
    paymentChart.setOption(option);
  });
};

// 新增柱状图数据获取方法
const getBarChartData = () => {
  axios.get("/dashboard/getBarChartData").then((res) => {
    const option = {
      xAxis: {
        data: res.data.map((item) => item.city_group),
      },
      yAxis: {},
      series: [
        {
          type: "bar",
          data: res.data.map((item) => item.total_amount),
          label: {
            show: true,
            position: "outside",
          },
        },
      ],
    };
    barChart.setOption(option);
  });
};

// 新增折线图数据获取方法
const getLineChartData = () => {
  axios.get("/dashboard/getLineChartData").then((res) => {
    // 获取所有不重复的月份并按时间排序
    const months = Array.from(new Set(res.data.map((item) => item.month))).sort(
      (a, b) => {
        const dateA = new Date(a);
        const dateB = new Date(b);
        return dateA - dateB;
      }
    );

    // 获取所有城市分组
    const cityGroups = Array.from(
      new Set(res.data.map((item) => item.city_group))
    );

    // 为每个城市分组创建系列数据
    const series = cityGroups.map((city) => {
      // 创建当前城市每个月份的数据点
      const cityData = res.data.filter((item) => item.city_group === city);

      const data = months.map((month) => {
        const item = cityData.find((d) => d.month === month);
        return item ? item.total_amount : null; // 使用null而不是0表示无数据
      });

      return {
        name: city,
        type: "line",
        data: data,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        lineStyle: {
          width: 3,
        },
        itemStyle: {
          color: getCityColor(city),
        },
        connectNulls: true, // 连接空值点
        emphasis: {
          focus: "series", // 高亮时只显示当前系列
          itemStyle: {
            borderWidth: 2,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowOffsetY: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      };
    });

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
        formatter: function (params) {
          let result = `<div style="font-weight:bold;margin-bottom:5px">${params[0].axisValue}</div>`;
          params.forEach((param) => {
            const value = param.value === null ? "无数据" : param.value;
            result += `
              <div style="display:flex;align-items:center;margin:3px 0">
                <span style="display:inline-block;width:10px;height:10px;background:${param.color};border-radius:50%;margin-right:5px"></span>
                ${param.seriesName}: <span style="font-weight:bold;margin-left:5px">${value}</span>
              </div>`;
          });
          return result;
        },
      },
      legend: {
        data: cityGroups,
        bottom: 10,
        itemWidth: 20,
        itemHeight: 10,
        textStyle: {
          fontSize: 12,
        },
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "60px",
        top: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: months,
        axisLabel: {
          formatter: function (value) {
            return value.replace("2025-", ""); // 显示更简洁的月份
          },
          interval: 0, // 强制显示所有标签
        },
        axisLine: {
          lineStyle: {
            color: "#ccc",
          },
        },
      },
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: "{value}",
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: "dashed",
          },
        },
      },
      series: series,
      animationDuration: 1000,
      animationEasing: "cubicOut",
    };

    lineChart.setOption(option);

    // 窗口大小变化时重新调整图表大小
    window.addEventListener("resize", function () {
      lineChart.resize();
    });
  });
};

// 为不同城市分配颜色
function getCityColor(city) {
  const colors = {
    上海: "#5470C6",
    北京: "#91CC75",
    广州: "#FAC858",
    深圳: "#EE6666",
  };
  return colors[city] || "#9A60B4";
}
</script>

<template>
  <div class="dashboard-container">
    <!-- 新增的折线图区域 -->
    <div class="dashboard-linechart">
      <el-card shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>近期营收趋势</span>
          </div>
        </template>
        <div class="chart-container">
          <div id="lineChart" style="width: 100%; height: 350px"></div>
        </div>
      </el-card>
    </div>

    <div class="dashboard-charts">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>订单统计</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="orderChart" style="width: 100%; height: 250px"></div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div class="chart-header">
                <span>支付方式统计</span>
              </div>
            </template>
            <div class="chart-container">
              <div id="paymentChart" style="width: 100%; height: 250px"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 柱状图区域 -->
    <div class="dashboard-barchart">
      <el-card shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>各城市总销售额</span>
          </div>
        </template>
        <div class="chart-container">
          <div id="barChart" style="width: 100%; height: 350px"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .dashboard-header {
    margin-bottom: 20px;

    .store-selector {
      width: 200px;

      :deep(.el-input__inner) {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        height: 40px;
        line-height: 40px;
      }

      :deep(.el-input__suffix) {
        display: flex;
        align-items: center;
      }
    }
  }

  /* 新增的折线图样式 */
  .dashboard-linechart {
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 350px;
    }
  }

  .dashboard-charts {
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 250px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  /* 柱状图样式 */
  .dashboard-barchart {
    margin-top: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 350px;
    }
  }
}
</style>
